<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="spu名称">
        <el-input v-model="spu.spuName" placeholder="spu的名称" />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option v-for="tm in trademarkList" :key="tm.id" :label="tm.tmName" :value="tm.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="spu描述">
        <el-input v-model="spu.description" placeholder="请输入描述内容" type="textarea" rows="3" />
      </el-form-item>
      <el-form-item label="spu图片">
        <!-- 照片墙 -->
        <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-success="handlerSuccess" :on-remove="handleRemove" :file-list="spuImageList">
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select v-model="attrIdAndAttrName" :placeholder="`还有${unSelectSaleAttr.length}个未选择`">
          <el-option v-for="unselect in unSelectSaleAttr" :key="unselect.id" :label="unselect.name" :value="`${unselect.id}:${unselect.name}`" />
        </el-select>
        <el-button type="primary" :disabled="!attrIdAndAttrName" icon="el-icon-plus" @click="addSaleAttr">添加销售属性</el-button>
        <!-- 展示的是当前spu属于自己的销售属性 -->
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column align="center" type="index" label="序号" width="80px" />
          <el-table-column prop="saleAttrName" label="属性名" width="width" />
          <el-table-column prop="prop" label="属性名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag v-for="(tag,index) in row.spuSaleAttrValueList" :key="tag.id" closable :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index,1)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!-- input -->
              <el-input v-if="row.inputVisible" ref="saveTagInput" v-model="row.inputValue" class="input-new-tag" size="mini" @keyup.enter.native="handleInputConfirm(row)" />
              <el-button v-else class="button-new-tag" size="mini" @click="showInput(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="{ row,$index }" label="操作" width="width">
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="spu.spuSaleAttrList.splice($index,1)" />
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SPUFORM',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu: {
        category3Id: 0,
        description: '',
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "",
          //   imgUrl: "",
          //   spuId: 0,
          // },
        ],
        spuName: '',
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "",
          //       saleAttrName: "",
          //       saleAttrValueName: "",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
        tmId: ''
      }, // spu信息属性
      trademarkList: [], // 品牌信息
      spuImageList: [], // spu图片信息
      saleAttrList: [], // 销售属性数据
      dynamicTags: ['标签一', '标签二', '标签三'],
      inputVisible: false,
      inputValue: '',
      attrIdAndAttrName: '' // 收集未选择的销售属性的id和值
    }
  },
  computed: {
    unSelectSaleAttr() {
      // 整个平台的销售属性有三个 颜色 尺寸 版本
      // 当前spu属性拥有的属于自己的销售属性
      const res = this.saleAttrList.filter(item => {
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name !== item1.saleAttrName
        })
      })
      return res
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.spuImageList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      // 对话框显示
      this.dialogVisible = true
    },
    // 照片墙图片上传成功的回调
    handlerSuccess(response, file, fileList) {
      // 收集图片的信息
      this.spuImageList = fileList
    },
    // 初始化spuform数据
    async initSpuDate(spu) {
      // 获取spu信息
      const spuRes = await this.$API.spu.reqGetSpu(spu.id)
      if (spuRes.code === 200) {
        this.spu = spuRes.data
      }
      // 获取品牌信息
      const trademarkRes = await this.$API.spu.reqTrademarkList()
      if (trademarkRes.code === 200) {
        this.trademarkList = trademarkRes.data
      }
      // 获取图片信息
      const spuImageListRes = await this.$API.spu.reqSpuImageList(spu.id)
      if (spuImageListRes.code === 200) {
        const listArr = spuImageListRes.data
        listArr.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = listArr
      }
      // 获取全部销售属性信息
      const baseSaleAttrListRes = await this.$API.spu.reqBaseSaleAttrList()
      if (baseSaleAttrListRes.code === 200) {
        this.saleAttrList = baseSaleAttrListRes.data
      }
    },
    // tag标签
    handleClose(tag) {},
    // 点击添加按钮的回调
    showInput(row) {
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'inputValue', '')
    },
    // input blur事件
    handleInputConfirm(row) {
      // 解构出销售属性中收集的数据
      const { baseSaleAttrId, inputValue } = row
      // 新增的销售属性不能为空
      if (inputValue.trim() === '') {
        this.$message('属性值不能为空')
        return
      }
      // 新增的销售属性不能重复
      const res = row.spuSaleAttrValueList.every(item => item.saleAttrValueName !== inputValue)
      if (!res) {
        this.$message('属性值不能重复')
        return
      }
      const temp = { baseSaleAttrId, saleAttrValueName: inputValue }
      row.spuSaleAttrValueList.push(temp)
      row.inputVisible = false
    },
    // 添加新的销售属性
    addSaleAttr() {
      // 已经收集需要添加的销售属性信息
      // 把收集到的销售属性数据进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      // 创建临时对象保存解构的销售属性
      const temp = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      // 添加新的销售属性
      this.spu.spuSaleAttrList.push(temp)
      this.attrIdAndAttrName = ''
    },
    // 保存信息
    addOrUpdateSpu() {
      // 整理参数 整理照片墙
      // 需要携带参数 imgname imgurl
      this.spu.spuImageList = this.spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url
        }
      })
      // 发送请求
      this.$API.spu
        .reqAddOrUpdateSpu(this.spu)
        .then(res => {
          this.$message({ type: 'success', message: '保存成功' })
          this.$emit('changeScene', 0)
        })
        .catch(err => {
          console.log(err)
        })
      // 清理数据
      Object.assign(this._data, this.$options.data())
    },
    // 点击添加spu按钮时,发请求的函数
    async addSpuData(category3Id) {
      // 收集三级分类id
      this.spu.category3Id = category3Id
      // 获取品牌信息
      const trademarkRes = await this.$API.spu.reqTrademarkList()
      if (trademarkRes.code === 200) {
        this.trademarkList = trademarkRes.data
      }
      // 获取全部销售属性信息
      const baseSaleAttrListRes = await this.$API.spu.reqBaseSaleAttrList()
      if (baseSaleAttrListRes.code === 200) {
        this.saleAttrList = baseSaleAttrListRes.data
      }
    },
    // 点击取消按钮
    cancel() {
      this.$emit('changeScene', 0)
      // 清理数据
      Object.assign(this._data, this.$options.data())
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
